package com.terminee.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.ClientProtocolException;

import android.net.Uri;

public class TermineeUtils {

	/**
	 * Return JSON array in string form from passed in URL
	 * @param url url to connect to
	 * @return JSON
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getResponseFromURL(Uri.Builder uriBuilder) throws Exception {
		
		// setup connection to URL
		URL url = new URL(uriBuilder.build().toString());
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setConnectTimeout(60000);
		conn.setRequestMethod("GET");
		conn.connect();
		
		// get results from url
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		StringBuilder json = new StringBuilder();
		String line = "";
		while ((line = rd.readLine()) != null) {
			json.append(line);
		}
		
		return json.toString();
	}
	
	public static String postStringToURL(Uri.Builder uriBuilder, String request) throws Exception {
		
		// setup connection to URL
		URL url = new URL(uriBuilder.build().toString());
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setConnectTimeout(60000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty( "Content-type", "text/plain" );
		conn.setRequestProperty( "Content-length", Integer.toString(request.length()));
		
		// write json to output stream
		PrintWriter out = new PrintWriter(conn.getOutputStream());
		out.print(request);
		out.flush();
		out.close();
		
		// get results from url
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		StringBuilder response = new StringBuilder();
		String line = "";
		while ((line = rd.readLine()) != null) {
			response.append(line);
		}
		
		return response.toString();
	}
}
